package com.wave.spring.web.controller;

import com.alibaba.fastjson.JSONObject;
import jmind.core.spring.CustomDateEditor;
import jmind.core.spring.GtLtEditor;
import jmind.core.spring.PrimitiveEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 *    通过@ControllerAdvice ，我们可以将对于控制器配置放置在同一个位置
 */
@ControllerAdvice
public class GlobalControllerAdvice {

    @ExceptionHandler({Throwable.class})
    public void handleException(Throwable e, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        JSONObject s = new JSONObject();
        s.put("code", Integer.valueOf(9999));
        s.put("msg", e.getMessage());

        try {
            request.setCharacterEncoding("UTF-8");
            response.getWriter().write(s.toJSONString());
        } catch (IOException var6) {
            var6.printStackTrace();
        }

    }

    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Date.class, new CustomDateEditor());
        binder.registerCustomEditor(String.class, new GtLtEditor());
        binder.registerCustomEditor(Integer.TYPE, new PrimitiveEditor(Integer.class));
        binder.registerCustomEditor(Float.TYPE, new PrimitiveEditor(Float.class));
        binder.registerCustomEditor(Long.TYPE, new PrimitiveEditor(Long.class));
        binder.registerCustomEditor(Short.TYPE, new PrimitiveEditor(Short.class));
        binder.registerCustomEditor(Double.TYPE, new PrimitiveEditor(Double.class));
    }

}
